const Minio = require('minio');
const ffmpeg = require('fluent-ffmpeg');
// MinIO 客户端配置
const minioClient = new Minio.Client({
    endPoint: global.config.minio_config.minio_endpoint,
    port: global.config.minio_config.minio_port,
    useSSL: global.config.minio_config.minio_use_ssl,
    accessKey: global.config.minio_config.minio_access_key,
    secretKey: global.config.minio_config.minio_secret_key
});

// minio中间件
const minioMiddleware = async (ctx, next) => {
    try {
        const file = ctx.req.file;
        if (!file) {
            throw new Error('No file uploaded');
        }

        const bucketName = global.config.minio_config.minio_bucket_name;
        
        // 确保bucket存在
        const bucketExists = await minioClient.bucketExists(bucketName);
        if (!bucketExists) {
            await minioClient.makeBucket(bucketName);
        }

        // 上传文件到MinIO
        const objectName = `${global.Moment().format('YYYY-MM-DD')}/${file.filename}`;
        await minioClient.fPutObject(
            bucketName,
            objectName,
            file.path
        );

        // 如果是视频，生成并上传缩略图
        if (file.filename.toLowerCase().endsWith('.mp4')) {
            const outputName = file.filename.replace('.mp4', '.jpg').replace('.MP4', '.jpg');
            const outputPath = `${file.destination}/${outputName}`;

            // 生成缩略图
            await new Promise((resolve, reject) => {
                ffmpeg(file.path)
                    .on('end', resolve)
                    .on('error', reject)
                    .screenshots({
                        count: 1,
                        folder: file.destination,
                        filename: outputName,
                        timestamps: ['00:00:02']
                    });
            });

            // 上传缩略图
            const thumbObjectName = objectName.replace('.mp4', '.jpg').replace('.MP4', '.jpg');
            await minioClient.fPutObject(
                bucketName,
                thumbObjectName,
                outputPath
            );

            // 将缩略图URL添加到ctx.state供后续使用
            ctx.state.thumbnailUrl = `http://${global.config.minio_config.minio_endpoint}:${global.config.minio_config.minio_port}/${bucketName}/${thumbObjectName}`;
        }

        // 将MinIO URL添加到ctx.state供后续使用
        ctx.state.minioUrl = `http://${global.config.minio_config.minio_endpoint}:${global.config.minio_config.minio_port}/${bucketName}/${objectName}`;
        
        await next();
    } catch (error) {
        console.error('MinIO middleware error:', error);
        ctx.throw(500, error.message);
    }
};

module.exports = minioMiddleware;